<template>
    <div class="main-container">
        <global />
        <div class="main-content">
            <div class="content-container">
                <div class="header">
                    <el-button type="success" @click="dialogVisible = true">新增课程</el-button>
                </div>

                <!-- 新增课程弹窗 -->
                <el-dialog v-model="dialogVisible" title="新增课程" width="40%">
                    <el-form :model="courseForm" label-width="100px">
                        <el-form-item label="课程编号">
                            <el-input v-model="courseForm.scCid" placeholder="请输入课程编号" />
                        </el-form-item>
                        <el-form-item label="课程名称">
                            <el-input v-model="courseForm.scName" placeholder="请输入课程名称" />
                        </el-form-item>
                        <el-form-item label="开设专业">
                            <el-select v-model="courseForm.scMajor" placeholder="请选择专业" style="width: 100%">
                                <el-option v-for="item in majorOptions" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="开设年级">
                            <el-select v-model="courseForm.scGrade" placeholder="请选择年级" style="width: 100%">
                                <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="开设班级">
                            <el-input v-model="courseForm.scClass" placeholder="请输入班级" />
                        </el-form-item>
                        <el-form-item label="授课教师工号">
                            <el-input v-model="courseForm.scTid" placeholder="请输入教师工号" disabled />
                        </el-form-item>
                        <el-form-item label="学期">
                            <el-select v-model="courseForm.scgSemester" placeholder="请选择学期" style="width: 100%">
                                <el-option v-for="item in semesterOptions" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="addCourse">确定</el-button>
                    </template>
                </el-dialog>

                <!-- 课程列表 -->
                <el-table :data="courseList" border style="width: 100%; margin-top: 20px;">
                    <el-table-column prop="scCid" label="课程编号" />
                    <el-table-column prop="scName" label="课程名称" />
                    <el-table-column prop="scMajor" label="开设专业" />
                    <el-table-column prop="scGrade" label="开设年级" />
                    <el-table-column prop="scClass" label="开设班级" />
                    <el-table-column prop="scgSemester" label="季度" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" @click="goToGradeManage(scope.row.scCid)"> >>> </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>

<script>
import { reactive, toRefs, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from '@/router/axios';
import { useRouter, useRoute } from "vue-router";
import { getSessionStorage } from '@/router/common';

export default {
    setup() {
        const router = useRouter();
        const route = useRoute();
        const state = reactive({
            dialogVisible: false,
            courseForm: {
                scCid: '',
                scName: '',
                scMajor: '',
                scGrade: '',
                scClass: '',
                scTid: getSessionStorage('teacher').tTid, // 自动填充教师工号
                scgSemester: ''
            },
            courseList: [],
            gradeOptions: [], // 年级下拉选项
            majorOptions: [],  // 专业下拉选项
            semesterOptions: []  // 学期下拉选项
        });

        // 初始化时获取下拉数据
        onMounted(() => {
            getGradeAndMajorOptions();
            initSemesterOptions();
            handleSearch();
        });

        // 初始化学期选项
        function initSemesterOptions() {
            const currentYear = new Date().getFullYear();
            const seasons = ['春季', '秋季'];
            const options = [];
            
            // 生成前后两年的学期选项
            for (let year = currentYear - 1; year <= currentYear + 1; year++) {
                for (const season of seasons) {
                    const value = `${year}年${season}期`;
                    const label = `${year}年${season}期`;
                    options.push({ value, label });
                }
            }
            
            state.semesterOptions = options;
        }

        function handleSearch() {
            axios.get('/api/teacher/class/getstulistbytid', {
                params: {
                    Tid: getSessionStorage('teacher').tTid
                }
            }).then(res => {
                const result = res.data;
                if (result.code == 1) {
                    state.courseList = result.data;
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        // 获取年级和专业数据
        function getGradeAndMajorOptions() {
            axios.get('api/teacher/student/getGradeAndSpecialty').then(res => {
                const result = res.data;
                if (result.code == 1) {
                    // 假设后端返回格式为 { grade: [...], major: [...]}
                    state.gradeOptions = result.data.grade.map(grade => ({
                        value: grade,
                        label: grade + '年级'
                    }));
                    state.majorOptions = result.data.major.map(major => ({
                        value: major,
                        label: major
                    }));
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        function addCourse() {
            // 表单验证（示例，实际需根据需求添加）
            if (!state.courseForm.scCid || !state.courseForm.scName) {
                ElMessage.error('课程编号和名称为必填项');
                return;
            }

            axios.post('/api/teacher/class/add', state.courseForm).then(res => {
                const result = res.data;
                if (result.code == 1) {
                    ElMessage.success('新增课程成功');
                    state.dialogVisible = false;
                    handleSearch();
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        function goToGradeManage(courseId) {
            router.push({
                name: 'gradeManage',
                query: {
                    courseId: courseId
                }
            });
        };

        return {
            ...toRefs(state),
            addCourse,
            goToGradeManage
        };
    },
};
</script>

<style scoped>
.main-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
}

.main-content {
    margin-left: 220px;
    margin-top: 60px;
    width: calc(100% - 220px);
    height: calc(100vh - 60px);
    overflow: auto;
}

.content-container {
    padding: 20px;
    min-height: calc(100% - 40px);
}

.header {
    margin-bottom: 20px;
}
</style>